package me.ycy.android.shuffle.synchronizer

import android.os.Bundle
import android.preference.{ PreferenceActivity, Preference }
import android.widget._
import android.content.Intent
import android.util.Log

class Preferences extends PreferenceActivity {
  val Tag = "ShuffleSync"

  def startStopSynchronizer(s: Boolean) = {
    try {
      val ctx = getApplicationContext
      if (s)
        ctx.startService(new Intent(this, classOf[ShuffleSynchronizer]))
      else
        ctx.stopService(new Intent(this, classOf[ShuffleSynchronizer]))
    }
    catch {
      case e => Log.e(Tag, e.getMessage)
    }
  }

  override def onCreate(savedInstanceState: Bundle) {
    super.onCreate(savedInstanceState)
    addPreferencesFromResource(R.xml.preferences)

    val enabledService = findPreference("serviceEnabled")
    enabledService.setOnPreferenceChangeListener(
      new Preference.OnPreferenceChangeListener {
        def onPreferenceChange(p: Preference, v: Object)  = {
          startStopSynchronizer(v.asInstanceOf[Boolean])
          true
        }
      }
    )

    val s = enabledService.getSharedPreferences.
      getBoolean(enabledService.getKey, false)
    startStopSynchronizer(s)
  }
}
